#!/usr/bin/bash
set -e

# 获取安装版本
echo -n "install flink version(1.17.1): "
read version

download_path="https://mirrors.tuna.tsinghua.edu.cn/apache/flink/flink-${version}/flink-${version}-bin-scala_2.12.tgz"
binary_name=`basename ${download_path}`

package_dir="/srv/package/"
install_dir="/srv/software/"
custom_env_file="/etc/profile.d/custom_env.sh"

# 创建存放目录，然后下载、安装、改名
mkdir -p ${package_dir} ${install_dir}
wget ${download_path} -P ${package_dir}
tar xf ${package_dir}${binary_name} -C ${install_dir}

# 添加环境变量
software_name=$(ls -l ${install_dir} |grep flink |grep ${version} |awk '{print $9}')
software_home=${install_dir}${software_name}
cat >> ${custom_env_file} <<-EOF
export FLINK_HOME=${software_home}
export PATH=\$FLINK_HOME/bin:\$PATH
EOF
source /etc/profile


# 配置 masters、workers
cat > ${software_home}/conf/masters <<-EOF
node1:8081
EOF

cat > ${software_home}/conf/workers <<-EOF
node1
node2
node3
EOF

# 修改 flink-conf.yaml 内容
sed -i '{
s/jobmanager.rpc.address: localhost/jobmanager.rpc.address: node1/
s/jobmanager.bind-host: localhost/jobmanager.bind-host: 0.0.0.0/
s/rest.address: localhost/rest.address: node1/
s/rest.bind-address: localhost/rest.bind-address: 0.0.0.0/
s/taskmanager.numberOfTaskSlots: 1/taskmanager.numberOfTaskSlots: 4/
s/taskmanager.host: localhost/taskmanager.host: node1/
s/taskmanager.bind-host: localhost/taskmanager.bind-host: 0.0.0.0/
}' ${software_home}/conf/flink-conf.yaml


# 分发配置，并修改 myid
scp -r ${software_home} node2:${install_dir}
scp -r ${software_home} node3:${install_dir}

scp ${custom_env_file} node2:${custom_env_file}
scp ${custom_env_file} node3:${custom_env_file}

ssh root@node2 "sed -i 's/taskmanager.host: node1/taskmanager.host: node2/' ${software_home}/conf/flink-conf.yaml"
ssh root@node3 "sed -i 's/taskmanager.host: node1/taskmanager.host: node3/' ${software_home}/conf/flink-conf.yaml"

# 安装成功提示
echo "Successfully installed flink..."